import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { Ajax } from "../../api/api";


export const DataSlice = createSlice({
    name: "DataSlice",
    initialState: {
        count: 2000,
        cartList: [],
        userInfo: null,
        cityList: [],
        city: null,
        goodList: [],
        goodType: [{
            text: '全部',
            value: '-1'
        }],
        fromPath: [],
    },
    reducers: {
        changeFromPath(state, { payload }) {
            state.fromPath.push(payload);
        },
        changeCount(state) {
            state.count++;
        },
        changeUserInfo(state, { payload }) {
            state.userInfo = payload;
        },
        changeCity(state, { payload }) {
            state.city = payload;
        },
        changeCartList(state, { payload }) {
            state.cartList = payload;
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(getUserInfoAsync.fulfilled, (state, action) => {
                state.userInfo = action.payload
            })
            .addCase(getCityListAsync.fulfilled, (state, action) => {
                state.cityList = action.payload.cities
            })
            .addCase(getGoodInfoAsync.fulfilled, (state, action) => {
                state.goodList = action.payload.goods
                state.goodType = [{ text: '全部', value: '-1' }, ...action.payload.types]
            })
            .addCase(getCartListAsync.fulfilled, (state, action) => {
                state.cartList = action.payload
            })
    }
})


export const { changeCount, changeUserInfo, changeCity, changeCartList, changeFromPath } = DataSlice.actions;

export const getUserInfoAsync = createAsyncThunk('data/userinfo', async (params?: any) => {
    let res = await Ajax.getuserinfo(params) as any;
    return res.result
})

export const getCityListAsync = createAsyncThunk('data/cityList', async (options?: any) => {
    const { params, headers } = options
    let res = await Ajax.getmaizuo(params, headers) as any;
    return res.result
})

export const getGoodInfoAsync = createAsyncThunk('data/goodInfo', async (options?: any) => {
    let res = await Ajax.getgooddata() as any;
    return res
})

export const getCartListAsync = createAsyncThunk('data/cartList', async (options?: any) => {
    let res = await Ajax.getcartlist() as any;
    return res.code == 200 ? res.result : []
})

export default DataSlice.reducer;